#include <iostream>
#include <cstring>
#include <memory>
#include "Log.hpp"
// 套接字四件套
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace std;
using namespace log;

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        LOG(LogLevel::ERROR) << "需要三个参数";
        exit(-1);
    }
    string server_ip = argv[1];
    int server_port = stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0); // 创建套接字文件
    LOG(LogLevel::INFO) << "服务器地址为:" << server_ip << ":" << server_port;
    struct sockaddr_in addr_server;                                                // 服务器地址结构
    memset(&addr_server, 0, sizeof(addr_server));                                  // 清空地址结构
    addr_server.sin_family = AF_INET;                                              // 设置为IPv4地址
    addr_server.sin_port = htons(server_port);                                     // 将端口号转换为网络字节序
    addr_server.sin_addr.s_addr = inet_addr(server_ip.c_str());                    // 将ip地址转换为网络字节序
    int n = connect(sockfd, (struct sockaddr *)&addr_server, sizeof(addr_server)); // 连接服务器
    if (n < 0)
    {
        LOG(LogLevel::ERROR) << "连接客户端失败";
        exit(-1);
    }
    else
    {
        LOG(LogLevel::INFO) << "连接服务器成功";
    }

    std::string message;
    while (1)
    {
        char buffer[1024];
        cout << "请输入要发送的消息:";
        getline(cin, message);
        n = write(sockfd, message.c_str(), message.size());
        if (n >= 0)
        {
            int m = read(sockfd, buffer, sizeof(buffer));
            if (m >= 0)
            {
                buffer[m] = 0;
                cout << "收到消息:" << buffer << endl;
            }
            else
            {
                LOG(LogLevel::ERROR) << "读取消息失败";
                break;
            }
        }
        else
        {
            LOG(LogLevel::ERROR) << "发送消息失败";
            break;
        }
    }

    close(sockfd);
    return 0;
}